package com.jky.trial.service.impl;

import com.jky.trial.common.ListResult;
import com.jky.trial.common.Pagination;
import com.jky.trial.entity.File;
import com.jky.trial.entity.FileExample;
import com.jky.trial.mapper.FileMapper;
import com.jky.trial.service.FileService;
import com.jky.trial.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    private final FileMapper recordMapper;


    @Autowired
    FileServiceImpl(FileMapper recordMapper) {

        this.recordMapper = recordMapper;
    }

    @Override
    public File saveFileInfo(String name, String desc1, String ownerId, Integer from, Integer type, String url, String extension, String originName, long size, Integer folderId) {
        File record = new File();
        record.setName(name);
        record.setDesc(desc1);
        record.setUrl(url);
        recordMapper.insertSelective(record);
        return record;
    }

    @Override
    public int create(File record) {
        record.setCreateAt(new Date());
        return recordMapper.insertSelective(record);
    }

    @Override
    public int update(File record) {
        FileExample recordExample = new FileExample();
        FileExample.Criteria criteria = recordExample.createCriteria();
        criteria.andIdEqualTo(record.getId());//查询条件
        return recordMapper.updateByExampleSelective(record, recordExample);
    }

    @Override
    public int del(int id) {
        File file = new File();
        file.setId(id);
        file.setDeleted(true);
        return recordMapper.updateByPrimaryKeySelective(file);
    }

    @Override
    public File detail(int id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<FileVo> list(FileVo record) {
        return recordMapper.pageList(record);
    }

    @Override
    public ListResult page(FileVo record) {
        List<FileVo> list = list(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public long count(File record) {
        FileExample recordExample = new FileExample();
        FileExample.Criteria criteria = recordExample.createCriteria();
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNameLike(record.getSearch());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        return recordMapper.countByExample(recordExample);
    }
}
